package com.lc.zpyh.ui.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.lc.umeng.UmengClient;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.request.SelectMyCartCountApi;
import com.lc.zpyh.http.request.SelectUserSchoolApi;
import com.lc.zpyh.http.request.VersionOfApi;
import com.lc.zpyh.http.response.SelectMyCartCountBean;
import com.lc.zpyh.http.response.VersionBean;
import com.lc.zpyh.http.response.selectUserSchoolBean;
import com.lc.zpyh.other.AppConfig;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.home.AddressSearchActivity;
import com.lc.zpyh.ui.dialog.UpdateDialog;
import com.lc.zpyh.ui.fragment.FindFoodFragment;
import com.lc.zpyh.ui.fragment.HomeFoodFragment;
import com.lc.zpyh.ui.fragment.MineFragment;
import com.lc.zpyh.ui.fragment.OrderFoodFragment;
import com.lc.zpyh.ui.fragment.SupermarketFragment;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.util.constant.EvenConstant;
import com.lc.zpyh.util.eventbus.Event;
import com.lc.zpyh.util.eventbus.EventBusUtils;
import com.lc.zpyh.widget.UIHelper;
import com.mob.secverify.PreVerifyCallback;
import com.mob.secverify.SecVerify;
import com.mob.secverify.common.exception.VerifyException;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import butterknife.ButterKnife;

public class MainActivity extends AppActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private static final String TAG = "MainActivity";
    private ClipboardManager clipboardManager;

    private boolean isPreVerifyDone = true;
    Fragment fragment = null;
    RadioGroup rgHomePageBottom;

    private RadioButton radioButton1, radioButton2, radioButton3, radioButton4;
    private ImageButton imageButton;

    private String startPageIndex;

    public static final int LOCATION_CODE = 301;
    private String locationProvider = null;
    private LocationManager locationManager;
    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    int presentInt = -1;
    private List<Fragment> mFragmentList;
    private FragmentTransaction mFragmentTransaction;
    private String userid;
//    {
//        mFragmentList.add(new HomeFoodFragment());
//        mFragmentList.add(new SupermarketFragment());
//        mFragmentList.add(new OrderFoodFragment());
//        mFragmentList.add(new MineFragment());
//        mFragmentList.add(new FindFoodFragment());
//    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        SPUtil.put(this,"hello","hello");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        UmengClient.init(getApplication());
        mFragmentList = new ArrayList<>();
        mFragmentList.add(new HomeFoodFragment());
        mFragmentList.add(new SupermarketFragment());
        mFragmentList.add(new OrderFoodFragment());
        mFragmentList.add(new MineFragment());
        mFragmentList.add(new FindFoodFragment());
        radioButton1 = findViewById(R.id.rb_home);
        radioButton2 = findViewById(R.id.rb_buy);
        radioButton4 = findViewById(R.id.rb_my);
        radioButton3 = findViewById(R.id.rb_find);
        rgHomePageBottom = findViewById(R.id.rg_home_page_bottom);
        rgHomePageBottom.setOnCheckedChangeListener(this);
        preVerify();
        radioButton1.setChecked(true);
            switchContent(mFragmentList.get(0));
            radioButton1=findViewById(R.id.rb_home);
            radioButton1.setChecked(true);
        VersionOf();



//        SPUtil.put(MainActivity.this, IntentKey.USERID, 1 + "");
        clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (SPUtil.get(getContext(), IntentKey.ADDRESSID, "").isEmpty() && SPUtil.get(getContext(), IntentKey.ADDRESS, "").isEmpty() || SPUtil.get(getContext(), IntentKey.ADDRESSID, "") == null) {
//            UIHelper.startActivity(getContext(), AddressSearchActivity.class);
            getLocation();
        }
    }

    private void VersionOf() {
        EasyHttp.get(this)
                .api(new VersionOfApi()
                        .setType("2")).request(new HttpCallback<VersionBean>(this) {


            @Override
            public void onSucceed(VersionBean data) {
                if (data.getList().getVersionCode()> AppConfig.getVersionCode()){
                    boolean isForcibly;
                    if (data.getList().getIsForcibly().equals("0")){
                        isForcibly=true;
                    }else {
                        isForcibly=false;
                    }
                    new UpdateDialog.Builder(MainActivity.this)
                            .setVersionName(data.getList().getVersion())
                            .setForceUpdate(isForcibly)
                            .setUpdateLog(Html.fromHtml(data.getList().getContent()))
                            .setDownloadUrl(data.getList().getDownloadUrl())
                            .show();
                }
//
            }


        });
    }

    private void preVerify() {

        isPreVerifyDone = false;
        //设置在1000-10000之内
        SecVerify.setTimeOut(4000);
        //移动的debug tag 是CMCC-SDK,电信是CT_ 联通是PriorityAsyncTask
        SecVerify.setDebugMode(true);
//        SecVerify.setUseCache(true);
        SecVerify.preVerify(new PreVerifyCallback() {
            @Override
            public void onComplete(Void data) {
                Log.e("TAG", "onComplete:-- " );
                // Nothing to do
//                if (devMode) {
//                    Toast.makeText(SplashActivity.this, "预登录成功", Toast.LENGTH_SHORT).show();
//                }

                isPreVerifyDone = true;
                SPUtil.put(MainActivity.this,"isPreVerifyDone",isPreVerifyDone);
            }

            @Override
            public void onFailure(VerifyException e) {
                isPreVerifyDone = true;
                // Nothing to do
                Throwable t = e.getCause();
                String errDetail = null;
                if (t != null){
                    errDetail = t.getMessage();
                }

//                if (devMode) {
//                 登录失败
                Log.e(TAG, "preVerify failed", e);
                // 错误码
                int errCode = e.getCode();
                // 错误信息
                String errMsg = e.getMessage();
                // 更详细的网络错误信息可以通过t查看，请注意：t有可能为null
                String msg = "错误码: " + errCode + "\n错误信息: " + errMsg;
                if (!TextUtils.isEmpty(errDetail)) {
                    msg += "\n详细信息: " + errDetail;
                }
                Log.e(TAG,msg);
                Toast.makeText(MainActivity.this, "预登陆失败", Toast.LENGTH_SHORT).show();
            }
//            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                copydata(MainActivity.this);
            }
        }, 500);
    }

    @Override
    protected void onStart() {
        super.onStart();
//        if (!SPUtil.get(getContext(), IntentKey.ADDRESSID, "").isEmpty() && !SPUtil.get(getContext(), IntentKey.USERID, "").isEmpty()) {
//            selectMyCartCount();
//        }
    }

    private void copydata(final Context context) {
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(context.CLIPBOARD_SERVICE);
        //无数据时直接返回
        if (!clipboard.hasPrimaryClip()) {
            return;
        }
        //如果是文本信息
        if (clipboard.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
            ClipData cdText = clipboard.getPrimaryClip();
            ClipData.Item item = cdText.getItemAt(0);
            //此处是TEXT文本信息
            if (item.getText() != null && !item.getText().toString().equals("")) {
                String str = item.getText().toString();
                EventBusUtils.sendEvent(new Event(EvenConstant.CLIPBOARD, str));
                Log.e(TAG, str);

            }
        }
    }

    private void selectMyCartCount() {
        if (SPUtil.get(getContext(), IntentKey.USERID, "") == null || SPUtil.get(getContext(), IntentKey.USERID, "").isEmpty()) {
            userid = "";
        } else {
            userid = SPUtil.get(getContext(), IntentKey.USERID, "");
        }
        EasyHttp.post(this)
                .api(new SelectMyCartCountApi().setSchoolId(SPUtil.get(getContext(), IntentKey.ADDRESSID, "")).setUserId(userid)).request(new HttpCallback<SelectMyCartCountBean>(this) {

            @Override
            public void onSucceed(SelectMyCartCountBean data) {
                if (data.getCode() == 0) {
                    SPUtil.put(MainActivity.this, IntentKey.CAR_COUNT, data.getList() + "");
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.rb_home:
                switchContent(mFragmentList.get(0));
                break;
            case R.id.rb_buy:
                switchContent(mFragmentList.get(1));
                break;
            case R.id.rb_find:
                switchContent(mFragmentList.get(2));
                break;
            case R.id.rb_my:
                switchContent(mFragmentList.get(3));
                break;
        }
    }

    private Fragment mContent = new Fragment();

    private void switchContent(Fragment to) {
        Log.e("addFragment", "### " + to.getId() + "  " + to.isAdded() + "  " + to.isHidden());
        if (mContent != to) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) {
                transaction.hide(mContent).add(R.id.fg_main, to).commitAllowingStateLoss();
            } else {
                transaction.hide(mContent).show(to).commitAllowingStateLoss();
            }
            mContent = to;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ib_mall:
                rgHomePageBottom.clearCheck();
                switchContent(mFragmentList.get(4));
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtils.show("再按一次退出程序");

            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    private void getLocation() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else
//        if (providers.contains(LocationManager.GPS_PROVIDER)) {
////如果是Network
            locationProvider = LocationManager.GPS_PROVIDER;
//        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
            if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //请求权限
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
            } else {
                //监视地理位置变化
                locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
                Location location = locationManager.getLastKnownLocation(locationProvider);
                if (location != null) {
                    //不为空,显示地理位置经纬度
                    selectUserSchool(location.getLongitude() + "", location.getLatitude() + "");
                } else {
                    EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXIN, "定位失败"));
                    EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXINID, "-1"));
                    SPUtil.put(MainActivity.this, IntentKey.ADDRESS, "定位失败");
                    SPUtil.put(MainActivity.this, IntentKey.ADDRESSID, "-1");
                }
            }
        } else {
            //监视地理位置变化
            locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
            Location location = locationManager.getLastKnownLocation(locationProvider);
            //不为空,显示地理位置经纬度
            if (location != null) {
                //不为空,显示地理位置经纬度
                selectUserSchool(location.getLongitude() + "", location.getLatitude() + "");
            } else {
                EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXIN, "定位失败"));
                EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXINID, "-1"));
                SPUtil.put(MainActivity.this, IntentKey.ADDRESS, "定位失败");
                SPUtil.put(MainActivity.this, IntentKey.ADDRESSID, "-1");
            }
        }
    }

    public LocationListener locationListener = new LocationListener() {
        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {
        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {
        }

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {

        }
    };

    //获取用户地址
    private void selectUserSchool(String jd, String wd) {
        if (SPUtil.get(getContext(), IntentKey.USERID, "") == null || SPUtil.get(getContext(), IntentKey.USERID, "").isEmpty()) {
            userid = "";
        } else {
            userid = SPUtil.get(getContext(), IntentKey.USERID, "");
        }
        EasyHttp.post(this)
                .api(new SelectUserSchoolApi().setUserid(userid).setJd(jd).setWd(wd)).request(new HttpCallback<selectUserSchoolBean>(this) {

            @Override
            public void onSucceed(selectUserSchoolBean data) {
                if (data.getCode() == 0) {
                    SPUtil.put(MainActivity.this, IntentKey.ADDRESS, data.getList().getName());
                    SPUtil.put(MainActivity.this, IntentKey.ADDRESSID, data.getList().getId());
//                       data.getList().getId()
                    EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXIN, data.getList().getName()));
                    EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXINID, data.getList().getId()));
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOCATION_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == getPackageManager().PERMISSION_GRANTED) {

                    try {
                        List<String> providers = locationManager.getProviders(true);
                        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                            //如果是Network
                            locationProvider = LocationManager.NETWORK_PROVIDER;
                        } else if (providers.contains(LocationManager.GPS_PROVIDER)) {
                            //如果是GPS
                            locationProvider = LocationManager.GPS_PROVIDER;
                        }
                        //监视地理位置变化
                        locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);
                        Location location = locationManager.getLastKnownLocation(locationProvider);
                        if (location != null) {
                            //不为空,显示地理位置经纬度
                            selectUserSchool(location.getLongitude() + "", location.getLatitude() + "");
                        } else {
                            EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXIN, "定位失败"));
                            EventBusUtils.sendEvent(new Event(EvenConstant.QUWANSHANXINID, "-1"));
                            SPUtil.put(MainActivity.this, IntentKey.ADDRESS, "定位失败");
                            SPUtil.put(MainActivity.this, IntentKey.ADDRESSID, "-1");
                        }
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    }
                } else {

                    UIHelper.startActivity(getContext(), AddressSearchActivity.class);
                }
                break;
        }
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        super.receiveEvent(event);
        if (event.getCode() == EvenConstant.TABALL || event.getCode() == EvenConstant.TABONE || event.getCode() == EvenConstant.TABTWO || event.getCode() == EvenConstant.TABTHREE || event.getCode() == EvenConstant.TABFOUR || event.getCode() == EvenConstant.TABFIVE) {
            //跳转不同的底部菜单
//            BaseApplication.INSTANCE.retainActivity(MainActivity.class);
            presentInt = (int) event.getData();
//         switchContent(mFragmentList.get(2));
            radioButton1.setChecked(false);
            radioButton2.setChecked(false);
            radioButton4.setChecked(false);
            radioButton3.setChecked(true);
        }
//
        Log.e(TAG, "receiveEvent:111111111111 ");
//
//     }
    }

    @Override
    protected void onSaveInstanceState(@NonNull @NotNull Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void receiveStickyEvent(Event event) {
        super.receiveStickyEvent(event);
        if (event.getCode() == EvenConstant.PAYSTAUTS) {
            radioButton1.setChecked(false);
            radioButton2.setChecked(false);
            radioButton4.setChecked(false);
            radioButton3.setChecked(true);

            switchContent(mFragmentList.get(2));
        }
    }
}
